#! /usr/bin/python

'''

This module is an actual driver program which will take SExpressions
and turn them into Python programs.

Usage:

SExpressionToPython sFile [pyFile]

If pyFile is not specified, it will be created with the same name
as the .s file, but with .py ending. 

@author kllvql
@date 12/24/11

'''

from ProjectFlags import *

TEST  = False
DEBUG = False

TEST  = TEST  or TEST_ALL
DEBUG = DEBUG or DEBUG_ALL




def _getPython(sExpression):
	'''
	Returns the string representation of a python file based off of 
	a given sExpression.
	'''
	
	from SExpressionToCodeTree import SExpressionToCodeTree as SEtoCT
	from CodeTreeToPython import CodeTreeToPython as CTtoP
	
	codeTree = SEtoCT(sExpression).getCodeTree()
	#print str(codeTree) +  '\n\n\n\n'
	pythonCode = str(CTtoP(codeTree))

	return pythonCode

def _readSExpression(filename):
	'''
	Returns an SExpression based off of a filename.
	'''
	from SExpression import SExpression
	
	sExp = SExpression.loadSExpression(filename)
	
	return sExp

def _writePython(filename, pythonCode):
	'''
	Writes the python file to filename.
	'''
	with open(filename, 'w') as thisFile:
		thisFile.write(pythonCode)
	
def createPython(sFile, pyFile):
	'''
	Method which ties it all together. I should probably refactor
	this to make fewer method calls, but that's something to look into
	later.
	'''
	#print sFile
	#print pyFile
	sExp = _readSExpression(sFile)
	#print '\nsExp:'
	#print sExp
	pythonCode = _getPython(sExp)
	#print '\n\npythonCode:'
	#print pythonCode
	_writePython(pyFile, pythonCode)


def test():
	print "SExpressionToPython.py testing..."
	
	print "End SExpressionToPython.py testing.\n"

if TEST:
	test()


def main(args):
	'''
	Main method which handles the optional parameters to this driver. 
	'''
	if len(args) > 2:
		createPython(args[1], args[2])
	else:
		createPython(args[1], args[1][:-1] + 'o.py')

if __name__ == '__main__':
	import sys
	main(sys.argv)
